package com.yunkaweilai.android.activity.operation.consumption.guadan;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.github.lazylibrary.util.PreferencesUtils;
import com.github.lazylibrary.util.StringUtils;
import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.CaptureActivity;
import com.yunkaweilai.android.activity.member.MemberInfoListActivity;
import com.yunkaweilai.android.activity.operation.CommonMemberActivity;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.constants.Umeng;
import com.yunkaweilai.android.interfaces.DialogMemberPayInterface;
import com.yunkaweilai.android.interfaces.DialogPayInterface;
import com.yunkaweilai.android.interfaces.PopupCouponSelector;
import com.yunkaweilai.android.interfaces.PopupDiscountSelector;
import com.yunkaweilai.android.interfaces.PopupIntegralMortgage;
import com.yunkaweilai.android.model.CheckMemberSendBean;
import com.yunkaweilai.android.model.CheckSendBean;
import com.yunkaweilai.android.model.CodeMsgBean;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.PayTypeModel;
import com.yunkaweilai.android.model.SendModel;
import com.yunkaweilai.android.model.member.MemberHeadModel;
import com.yunkaweilai.android.model.operation.CreateSelectedGoodsModel;
import com.yunkaweilai.android.model.operation.ReceivablesCreatOrderModel;
import com.yunkaweilai.android.model.order.IntegralMortgageModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.view.dialog.PayErrorDialog;
import com.yunkaweilai.android.view.dialog.member.MemberPassDialog;
import com.yunkaweilai.android.view.dialog.operation.DialogPayMoney;
import com.yunkaweilai.android.view.dialog.operation.OperationPayCashDialog;
import com.yunkaweilai.android.view.dialog.operation.OperationPayDialog;
import com.yunkaweilai.android.view.popup.IntegralMortgagePopup;
import com.yunkaweilai.android.view.popup.MemberCouponPopup;
import com.yunkaweilai.android.view.popup.PreferentialActivitiesPopup;
import com.zhy.m.permission.MPermissions;
import com.zhy.m.permission.PermissionDenied;
import com.zhy.m.permission.PermissionGrant;

import org.greenrobot.eventbus.EventBus;

import java.util.Calendar;
import java.util.TimeZone;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.addapp.pickers.picker.DatePicker;

/**
 * 收款界面
 * Created by Administrator on 2017/7/13.
 */

public class GuadanReceivablesActivity extends BaseActivity implements PopupDiscountSelector, PopupIntegralMortgage, DialogPayInterface, DialogMemberPayInterface, PopupCouponSelector {

    public static final String RECEIVABLES_PRICE = "RECEIVABLES_PRICE";
    public static final String SELECTED_GOOD_STR = "SELECTED_GOOD_STR";
    public static final String CREATE_HEEP_URL = "CREATE_HEEP_URL";
    public static final String GUADAN_GID = "GUADAN_GID";
    public static final String RECEIVABLE_TURN_TYPE = "RECEIVABLE_TURN_TYPE";
    public static final String GUADAN_FANGFEI = "GUADAN_FANGFEI";

    public static final int SEARCH_MEMBER = 501;//搜索会员
    @BindView(R.id.titlebar_iv_left)
    ImageView titlebarIvLeft;
    @BindView(R.id.titlebar_tv_left)
    TextView titlebarTvLeft;
    @BindView(R.id.titlebar_tv)
    TextView titlebarTv;
    @BindView(R.id.titlebar_iv_right_2)
    ImageView titlebarIvRight2;
    @BindView(R.id.titlebar_iv_right)
    ImageView titlebarIvRight;
    @BindView(R.id.titlebar_tv_right)
    TextView titlebarTvRight;
    @BindView(R.id.id_view_underline)
    View idViewUnderline;
    @BindView(R.id.rl_titlebar)
    RelativeLayout rlTitlebar;
    @BindView(R.id.id_rb_fit)
    RadioButton idRbFit;
    @BindView(R.id.id_rb_member)
    RadioButton idRbMember;
    @BindView(R.id.id_rgp_selecotr)
    RadioGroup idRgpSelecotr;
    @BindView(R.id.id_img_head)
    ImageView idImgHead;
    @BindView(R.id.id_tv_name)
    TextView idTvName;
    @BindView(R.id.id_tvcard_number)
    TextView idTvcardNumber;
    @BindView(R.id.id_tv_card_infor)
    TextView idTvCardInfor;
    @BindView(R.id.linearLayout)
    LinearLayout linearLayout;
    @BindView(R.id.id_tv_right_price)
    TextView idTvRightPrice;
    @BindView(R.id.id_tv_fit_price)
    TextView idTvFitPrice;
    @BindView(R.id.id_tv_member_price)
    TextView idTvMemberPrice;
    @BindView(R.id.id_activity_left)
    TextView idActivityLeft;
    @BindView(R.id.id_tv_activity_info)
    TextView idTvActivityInfo;
    @BindView(R.id.id_llayout_activity)
    LinearLayout idLlayoutActivity;
    @BindView(R.id.id_tv_coupon_left)
    TextView idTvCouponLeft;
    @BindView(R.id.id_tv_coupon_right)
    TextView idTvCouponRight;
    @BindView(R.id.id_llayout_coupon)
    LinearLayout idLlayoutCoupon;
    @BindView(R.id.id_view_integral)
    View idViewIntegral;
    @BindView(R.id.id_tv_integer_left)
    TextView idTvIntegerLeft;
    @BindView(R.id.id_tv_integral_info)
    TextView idTvIntegralInfo;
    @BindView(R.id.id_llayout_integer)
    LinearLayout idLlayoutInteger;
    @BindView(R.id.id_tv_now_money)
    TextView idTvNowMoney;
    @BindView(R.id.id_tv_get_integral)
    TextView idTvGetIntegral;
    @BindView(R.id.id_llayout_get_integer)
    LinearLayout idLlayoutGetInteger;
    @BindView(R.id.id_rb_cash)
    RadioButton idRbCash;
    @BindView(R.id.id_rb_bank)
    RadioButton idRbBank;
    @BindView(R.id.id_rb_zfb)
    RadioButton idRbZfb;
    @BindView(R.id.id_rb_wx)
    RadioButton idRbWx;
    @BindView(R.id.id_rb_yue)
    RadioButton idRbYue;
    @BindView(R.id.id_rdg)
    RadioGroup idRdg;
    @BindView(R.id.id_edt_pey_money)
    TextView idEdtPeyMoney;
    @BindView(R.id.id_llayout_cash)
    LinearLayout idLlayoutCash;
    @BindView(R.id.id_tv_remarks)
    EditText idTvRemarks;
    @BindView(R.id.content_view)
    ScrollView contentView;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    @BindView(R.id.id_tv_actual)
    TextView idTvActual;
    @BindView(R.id.id_tv_actual_money)
    TextView idTvActualMoney;
    @BindView(R.id.id_tv_confirm)
    TextView idTvConfirm;
    @BindView(R.id.id_member_layout)
    View idMemberHeaderLayout;
    @BindView(R.id.id_llayout_now_money)
    LinearLayout idLlayoutNowMoney;
    @BindView(R.id.id_tv_tuisong)
    TextView idTvTuisong;
    @BindView(R.id.id_check_sms)
    CheckBox idCheckSms;
    @BindView(R.id.id_check_vx)
    CheckBox idCheckVx;
    @BindView(R.id.id_check_print)
    CheckBox idCheckPrint;
    @BindView(R.id.id_check_next)
    CheckBox idCheckNext;
    @BindView(R.id.id_tv_commission_name)
    TextView idTvCommissionName;
    @BindView(R.id.id_rl_commission_people)
    LinearLayout idRlCommissionPeople;
    @BindView(R.id.id_img_now_money)
    ImageView idImgNow;
    @BindView(R.id.line_to_member)
    LinearLayout linearLayoutToMember;
    private boolean open_sms = false;
    private boolean sms = false;
    private boolean wechat = false;
    private boolean print = false;

    private MemberHeadModel model;
    private Gson gson = new Gson();
    private String price;
    private boolean isMember = false;
    private IntegralMortgageModel integralMortgageModel;

    private String discountId = "0";//优惠活动id
    private String payment_type = "cash";//支付方式
    private String SelectedGoodsStr = "";//商品字符串
    private String httpUrl = "";//接口url
    private String gid;//挂单消费id，其他消费不用管
    private String zhaoLing = "";
    private String balance_price = "0";
    private String cash_price = "0";
    private String bank_price = "0";
    private String wechat_price = "0";
    private String alipay_price = "0";
    private String pey_money = "0";
    private String coupon_no = "0";
    private String type;//跳转的来源
    private String points_replace_points = "0";
    private String fangfei = "";
    private PayTypeModel payModel;
    private boolean isCouponClean = true;
    private String z_special_points = "0";
    private String special_points_price = "0";

    public static void actionStart(Context context, String price, String SelectedGoodsStr, String url, String gid, String type, String fangfei) {
        Intent intent = new Intent(context, GuadanReceivablesActivity.class);
        intent.putExtra(RECEIVABLES_PRICE, price);
        intent.putExtra(SELECTED_GOOD_STR, SelectedGoodsStr);
        intent.putExtra(CREATE_HEEP_URL, url);
        intent.putExtra(GUADAN_GID, gid);
        intent.putExtra(RECEIVABLE_TURN_TYPE, type);
        intent.putExtra(GUADAN_FANGFEI, fangfei);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receivables);
        ButterKnife.bind(this);
        if (!(BaseApplication.getPayModel().getData().getInfo().getIs_edit_payment() == null) &&!BaseApplication.getPayModel().getData().getInfo().getIs_edit_payment().equals("1")){
            idImgNow.setVisibility(View.GONE);
        }
        //让详情先显示出来
        linearLayoutToMember.setVisibility(View.VISIBLE);

        boolean aBoolean = PreferencesUtils.getBoolean(mAc, CommonConstants.GUADAN_DAYING, false);
        idCheckPrint.setChecked(aBoolean);
        type = getIntent().getStringExtra(RECEIVABLE_TURN_TYPE);
        price = getIntent().getStringExtra(RECEIVABLES_PRICE);
        SelectedGoodsStr = getIntent().getStringExtra(SELECTED_GOOD_STR);
        httpUrl = getIntent().getStringExtra(CREATE_HEEP_URL);
        gid = getIntent().getStringExtra(GUADAN_GID);
        fangfei = getIntent().getStringExtra(GUADAN_FANGFEI);
        new TitleBuilder(mAc).setLeftImage(R.mipmap.ic_go_back)
                .setLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                }).setTitleText("收款");
        initGetTuisong2();
        clickable(false, "sms");
        clickable(false, "wechat");
        clickable(false, "next");
        initOtherView();
        initClick();
        initView();
        initDate();
        initGetTuisong2();
    }

    private void initGetTuisong(final boolean sms, final boolean wechat) {
        HttpRequest.postUrl(Api.GET_SEND_STATUS)
                .addParams("send_view", "Guadan")
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            SendModel sendModel = gson.fromJson(json, SendModel.class);
                            if (sendModel != null) {
                                if ("1".equals(sendModel.getData().getInfo().getSend_sms_status())) {
                                    if (sms) {
                                        idCheckSms.setChecked(true);
                                    } else {
                                        idCheckSms.setChecked(false);
                                    }
                                }
                                if ("1".equals(sendModel.getData().getInfo().getSend_wechat_status())) {
                                    if (wechat) {
                                        idCheckVx.setChecked(true);
                                    } else {
                                        idCheckVx.setChecked(false);
                                    }
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                    }
                });
    }

    private void initGetTuisong2() {
        HttpRequest.postUrl(Api.CHECK_SEND)
                .addParams("view", "consumemember")
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkcode = Utils.checkCode(mAc, json);
                        if (checkcode) {
                            Gson gson = new Gson();
                            CheckSendBean checkSendBean = gson.fromJson(json, CheckSendBean.class);
                            if (checkSendBean.getData().getIs_check_print().equals("1")) {
                                print = true;
                                idCheckPrint.setClickable(true);
                                idCheckPrint.setAlpha((float) 1);
                            } else {
                                print = false;
                                idCheckPrint.setClickable(false);
                                idCheckPrint.setAlpha((float) 0.3);
                                idCheckPrint.setChecked(false);//避免切换账号以后打钩残留的问题
                            }
                            if (checkSendBean.getData().getIs_send_sms().equals("1")) {
                                open_sms = true;
                            } else {
                                open_sms = false;
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        showToast(e.getMessage());
                    }
                });
    }

    private void clickable(boolean able, String type) {
        if (able) {
            if (type.equals("sms")) {
                idCheckSms.setClickable(true);
                idCheckSms.setAlpha((float) 1);
            }
            if (type.equals("wechat")) {
                idCheckVx.setClickable(true);
                idCheckVx.setAlpha((float) 1);
            }
            if (type.equals("next")) {
                idCheckNext.setClickable(true);
                idCheckNext.setAlpha((float) 1);
            }
        } else {
            if (type.equals("sms")) {
                idCheckSms.setClickable(false);
                idCheckSms.setAlpha((float) 0.3);
            }
            if (type.equals("wechat")) {
                idCheckVx.setClickable(false);
                idCheckVx.setAlpha((float) 0.3);
            }
            if (type.equals("next")) {
                idCheckNext.setClickable(false);
                idCheckNext.setAlpha((float) 0.3);
            }
        }
    }

    private void selectMember(String card_no) {
        HttpRequest.postUrl(Api.CONSUME_MEMBER)
                .addParams("keyword", card_no)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkcode = Utils.checkCode(mAc, json);
                        if (checkcode) {

                            Gson gson = new Gson();
                            CheckMemberSendBean checkMemberSendBean = gson.fromJson(json, CheckMemberSendBean.class);
                            if (!StringUtils.isEmpty(checkMemberSendBean.getData().getMemberInfo().getMember_tel()) && open_sms) {
                                clickable(true, "sms");
                                sms = true;
                            } else {
                                clickable(false, "sms");
                                sms = false;
                            }
                            if (checkMemberSendBean.getData().getMemberInfo().getIs_push_wechat() == 1) {
                                clickable(true, "wechat");
                                wechat = true;
                            } else {
                                clickable(false, "wechat");
                                wechat = false;
                            }
                            initGetTuisong(sms, wechat);
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        showToast(e.getMessage());
                    }
                });
    }

    private int mYear, mMonth, mDay;

    private void initDate() {
        final Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        mYear = c.get(Calendar.YEAR);// 获取当前年份
        mMonth = c.get(Calendar.MONTH) + 1;// 获取当前月份
        mDay = c.get(Calendar.DAY_OF_MONTH);// 获取当前月份的日期号码
    }

    private void initOtherView() {
        payModel = BaseApplication.getPayModel();
        if (payModel != null) {
            if ("1".equals(payModel.getData().getInfo().getIs_bank_pay())) {
                idRbBank.setVisibility(View.VISIBLE);
            } else {
                idRbBank.setVisibility(View.GONE);
            }
            if ("1".equals(payModel.getData().getInfo().getIs_wechat_pay())) {
                idRbWx.setVisibility(View.VISIBLE);
            } else {
                idRbWx.setVisibility(View.GONE);
            }
            if ("1".equals(payModel.getData().getInfo().getIs_alipay())) {
                idRbZfb.setVisibility(View.VISIBLE);
            } else {
                idRbZfb.setVisibility(View.GONE);
            }
        }
    }


    private void initView() {
        price = Utils.ManageMoney(price);
        pey_money = price;
        idTvFitPrice.setText(price);
        idTvMemberPrice.setText(price);
        idTvNowMoney.setText(price + "");
        idEdtPeyMoney.setText(price + "");
        idTvActualMoney.setText(price + "");

        Drawable drawable = getResources().getDrawable(R.drawable.selector_checkbox_style);
        //设置drawable对象的大小
        drawable.setBounds(0, 0, 40, 40);
        Drawable drawable2 = getResources().getDrawable(R.drawable.selector_checkbox_style);
        //设置drawable对象的大小
        drawable2.setBounds(0, 0, 40, 40);
        Drawable drawable3 = getResources().getDrawable(R.drawable.selector_checkbox_style);
        //设置drawable对象的大小
        drawable3.setBounds(0, 0, 40, 40);
        Drawable drawable4 = getResources().getDrawable(R.drawable.selector_checkbox_style);
        //设置drawable对象的大小
        drawable4.setBounds(0, 0, 40, 40);
        idCheckSms.setCompoundDrawables(drawable, null, null, null);
        idCheckVx.setCompoundDrawables(drawable2, null, null, null);
        idCheckPrint.setCompoundDrawables(drawable3, null, null, null);
        idCheckNext.setCompoundDrawables(drawable4, null, null, null);

    }

    private void initClick() {
        idRbFit.setChecked(true);
        idRbCash.setChecked(true);
        initMemberOrFit(false);
        idRgpSelecotr.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.id_rb_fit:
                        initMemberOrFit(false);
                        idTvFitPrice.setText(price);
                        idTvMemberPrice.setText(price);
                        idTvNowMoney.setText(Utils.ManageMoney(price));
                        idEdtPeyMoney.setText(Utils.ManageMoney(price));
                        idTvActualMoney.setText(Utils.ManageMoney(price));
                        isMember = false;
                        model = null;
                        clickable(false, "sms");
                        clickable(false, "wechat");
                        clickable(false, "next");
                        idCheckSms.setChecked(false);
                        idCheckVx.setChecked(false);
                        idCheckNext.setChecked(false);
                        break;
                    case R.id.id_rb_member:
                        startActivityForResult(new Intent(mAc, CommonMemberActivity.class), SEARCH_MEMBER);
                        break;
                }
            }
        });
        idRdg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.id_rb_bank:
                        payment_type = "bank";
                        idLlayoutCash.setVisibility(View.GONE);
                        break;
                    case R.id.id_rb_cash:
                        payment_type = "cash";
                        idLlayoutCash.setVisibility(View.VISIBLE);
                        idEdtPeyMoney.setText(idTvNowMoney.getText().toString() + "");
                        break;
                    case R.id.id_rb_wx:
                        payment_type = "wechat";
                        idLlayoutCash.setVisibility(View.GONE);
                        break;
                    case R.id.id_rb_zfb:
                        payment_type = "alipay";
                        idLlayoutCash.setVisibility(View.GONE);
                        break;
                    case R.id.id_rb_yue:
                        payment_type = "balance";
                        idLlayoutCash.setVisibility(View.GONE);
                        break;
                }
            }
        });
        idCheckPrint.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                PreferencesUtils.putBoolean(mAc, CommonConstants.GUADAN_DAYING, isChecked);
            }
        });
        idCheckSms.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                saveSendStatus("send_sms", isChecked, idCheckSms);
            }
        });
        idCheckVx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                saveSendStatus("send_wechat", isChecked, idCheckVx);
            }
        });
        idCheckNext.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if ("再次消费提醒".equals(idCheckNext.getText().toString())) {
                        idCheckNext.setChecked(false);
                        initPickerData(idCheckNext);
                    }
                } else {
                    idCheckNext.setText("再次消费提醒");
                }
            }
        });

    }

    //时间选择
    private void initPickerData(final CheckBox tvView) {
        final DatePicker picker = new DatePicker(this);
        picker.setCanLoop(false);
        picker.setWheelModeEnable(true);
        picker.setTopPadding(15);
        picker.setRangeStart(2018, 1, 01);
        picker.setRangeEnd(2108, 11, 11);
        picker.setSelectedItem(mYear, mMonth, mDay);
        picker.setWeightEnable(true);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                tvView.setText(year + "-" + month + "-" + day);
                tvView.setChecked(true);
            }
        });
        picker.setOnWheelListener(new DatePicker.OnWheelListener() {
            @Override
            public void onYearWheeled(int index, String year) {
                picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
            }

            @Override
            public void onMonthWheeled(int index, String month) {
                picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
            }

            @Override
            public void onDayWheeled(int index, String day) {
                picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
            }
        });
        picker.show();
    }

    private void saveSendStatus(String sendType, boolean status, final CheckBox checkBox) {
        HttpRequest.postUrl(Api.SAVE_SEND_STATUS)
                .addParams("send_status", status ? "1" : "0")
                .addParams("send_type", sendType)
                .addParams("send_view", "Guadan")
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (!checkCode) {
                            checkBox.setChecked(false);
                        }
                    }

                    @Override
                    public void onError(Exception e) {

                    }
                });
    }


    // 切换散客会员后的状态
    public void initMemberOrFit(boolean flag) {
        idTvRemarks.clearFocus();
        if (flag) {
            idMemberHeaderLayout.setVisibility(View.VISIBLE);
            idTvMemberPrice.setVisibility(View.VISIBLE);
            idTvMemberPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            idLlayoutInteger.setVisibility(View.VISIBLE);
            contentView.setFocusable(true);
            contentView.setFocusableInTouchMode(true);
            contentView.requestFocus();
            idLlayoutGetInteger.setVisibility(View.VISIBLE);
            idViewIntegral.setVisibility(View.VISIBLE);
            if ("1".equals(model.getIs_stored())) {
                idRbYue.setVisibility(View.VISIBLE);
                idRbYue.setChecked(true);
            } else {
                idRbYue.setVisibility(View.GONE);
                idRbCash.setChecked(true);
            }
        } else {
            idRbCash.setChecked(true);
            idMemberHeaderLayout.setVisibility(View.GONE);
            idViewIntegral.setVisibility(View.GONE);
            idTvMemberPrice.setVisibility(View.GONE);
            idLlayoutInteger.setVisibility(View.GONE);
            idRbYue.setVisibility(View.GONE);
            idLlayoutGetInteger.setVisibility(View.GONE);
        }
        idTvActivityInfo.setText("");
        idTvIntegralInfo.setText("");
        idTvGetIntegral.setText("");
        idTvRemarks.setText("");
        coupon_no = "0";
        discountId = "0";
        idActivityLeft.setText("优惠活动");
        idTvCouponLeft.setText("优惠券");
        idTvIntegerLeft.setText("积分抵扣");
        idTvCouponRight.setText("");
        contentView.scrollTo(0, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 501://选择会员
                    isMember = data.getBooleanExtra(CommonMemberActivity.SEARCH_MEMBER_FLAG, false);
                    if (isMember) {
                        model = (MemberHeadModel) data.getBundleExtra(CommonMemberActivity.SEARCH_MEMBER_BUNDLE).getSerializable(CommonMemberActivity.SEARCH_MEMBER_MODEL);
                        initMemberHeader();
                        clickable(true, "next");
                        selectMember(model.getCard_no());
                        if ("1".equals(model.getIs_arrived_points())) {
                            idLlayoutInteger.setVisibility(View.VISIBLE);
                            idViewIntegral.setVisibility(View.VISIBLE);
                        } else {
                            idLlayoutInteger.setVisibility(View.GONE);
                            idViewIntegral.setVisibility(View.GONE);
                        }
                        initMemberOrFit(true);
                        getPayment();
                    } else {
                        idRbFit.setChecked(true);
                        initMemberOrFit(false);
                    }

                    break;
                case 101:
                    Bundle bundle = data.getExtras();
                    if (bundle == null) {
                        return;
                    }
                    String result = bundle.getString(CaptureActivity.RESULT);
                    showProgressDialog("请稍等，正在支付中！");
                    initOrder2(result);
                    break;

            }
        }
    }

    private void initMemberHeader() {
        Utils.MemberHeadImg(mAc, model.getMember_avatar(), model.getMember_sex(), idImgHead);
        idTvName.setText(model.getMember_name() + " (" + model.getLevel_name() + ": " + model.getCard_no() + ")");
        idTvCardInfor.setText("折扣：" + model.getDiscount() / 10 + "折   积分：" + model.getMember_points() + "   余额：" + model.getMember_price());

    }

    @OnClick({R.id.line_to_member, R.id.id_img_head, R.id.id_tv_now_money, R.id.id_edt_pey_money, R.id.id_member_layout, R.id.id_llayout_activity, R.id.id_llayout_coupon, R.id.id_llayout_integer, R.id.id_rl_commission_people, R.id.id_tv_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.line_to_member:
                MemberInfoListActivity.actionStart(mAc, model,"2");
                break;
            case R.id.id_tv_now_money://实收金额
                if (!(BaseApplication.getPayModel().getData().getInfo().getIs_edit_payment() == null) &&BaseApplication.getPayModel().getData().getInfo().getIs_edit_payment().equals("1")) {
                    new DialogPayMoney(mAc, R.style.dialog, new DialogPayMoney.OnCloseListener() {
                        @Override
                        public void onClick(Dialog dialog, boolean confirm, String content) {
                            if (confirm) {
                                idTvNowMoney.setText(Utils.ManageMoney(content));
                                idTvActualMoney.setText(Utils.ManageMoney(content));
                                idEdtPeyMoney.setText(Utils.ManageMoney(content));
                                getPoint(content, "1");
                                dialog.dismiss();
                            }
                        }
                    }, idTvNowMoney.getText().toString(), "修改实收金额").show();
                }else {
//                    showToast("无修改实收金额权限");
                }
                break;
            case R.id.id_edt_pey_money://现金支付时输入金额
                new DialogPayMoney(mAc, R.style.dialog, new DialogPayMoney.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm, String content) {
                        if (confirm) {
                            if (!StringUtils.isEmpty(idTvNowMoney.getText().toString()) && !StringUtils.isEmpty(content + "")) {
                                idEdtPeyMoney.setText(Utils.ManageMoney(content));
                            }
                            dialog.dismiss();
                        }
                    }
                }, idEdtPeyMoney.getText().toString(), "收款金额").show();
                break;
            case R.id.id_llayout_activity://优惠活动
                PreferentialActivitiesPopup preferentialActivitiesPopup = new PreferentialActivitiesPopup(mAc, isMember ? model.getId() : "0", pey_money);
                preferentialActivitiesPopup.setPopupDiscountSelector(this);
                preferentialActivitiesPopup.showPopupWindow();
                break;
            case R.id.id_llayout_coupon://优惠券
                MemberCouponPopup memberCouponPopup = new MemberCouponPopup(mAc, isMember ? model.getId() : "0", SelectedGoodsStr, discountId, price, points_replace_points, fangfei, false, idTvNowMoney.getText().toString());
                memberCouponPopup.setPopupDiscountSelector(this);
                memberCouponPopup.showPopupWindow();
                break;
            case R.id.id_llayout_integer://积分抵用
                if ("1".equals(model.getIs_points()) && "1".equals(model.getIs_arrived_points())) {
                    IntegralMortgagePopup integralMortgagePopup = new IntegralMortgagePopup(mAc, model);
                    integralMortgagePopup.setPopupInterfaces(this);
                    integralMortgagePopup.showPopupWindow();
                } else {
                    showToast("还未开启积分规则!");
                }
                break;
            case R.id.id_tv_confirm://确认收款
                isRight();
                break;
            case R.id.id_member_layout://选择会员
                startActivityForResult(new Intent(mAc, CommonMemberActivity.class), SEARCH_MEMBER);
                break;

            case R.id.id_img_head:
                Utils.ImageEnlage(mAc, "1", model.getMember_avatar(), model.getMember_sex());
                break;
        }
    }

    //创建订单验证
    private void isRight() {
        if (payment_type.equals("balance")) {
            if ("1".equals(model.getIs_password()) && !Utils.isEmpty(model.getPay_password())) {
                MemberPassDialog dialog = new MemberPassDialog(mAc, this);
                dialog.show();
            } else {
                OperationPayDialog dialog = new OperationPayDialog(mAc, "￥ " + idTvNowMoney.getText().toString(), this, payment_type);
                dialog.show();
            }
        } else if (payment_type.equals("cash")) {
            if ("输入金额".equals(idEdtPeyMoney.getText().toString())) {
                showToast("未填写收款金额");
                return;
            }
            OperationPayCashDialog dialog = new OperationPayCashDialog(mAc, idTvNowMoney.getText().toString(), idEdtPeyMoney.getText().toString(), this);
            dialog.show();
        } else {
            PayTypeModel.DataBean.InfoBean info = payModel.getData().getInfo();
            if (payment_type.equals("wechat")) {
                if ("MtoS".equals(info.getWechat_scan_pay_type())) {
                    OperationPayDialog dialog = new OperationPayDialog(mAc, "￥ " + idTvNowMoney.getText().toString(), this, payment_type);
                    dialog.show();
                } else {
                    //调用扫码
                    getCameraManifest();
                }
            } else if (payment_type.equals("alipay")) {
                if ("MtoS".equals(info.getAlipay_scan_pay_type())) {
                    OperationPayDialog dialog = new OperationPayDialog(mAc, "￥ " + idTvNowMoney.getText().toString(), this, payment_type);
                    dialog.show();
                } else {
                    //调用扫码
                    getCameraManifest();
                }
            } else {
                OperationPayDialog dialog = new OperationPayDialog(mAc, "￥ " + idTvNowMoney.getText().toString(), this, payment_type);
                dialog.show();
            }
        }
    }

    //选择优惠活动
    @Override
    public void updateInfo(String left, String right, String discountid) {
        idActivityLeft.setText("优惠活动" + left);
        idTvActivityInfo.setText(right + "");
        this.discountId = discountid;
        getPayment();
    }

    //获取应支付金额
    private void getPayment() {
        HttpRequest.postUrl(Api.CREATE_SELECTED_GOODS)
                .addParams("SelectedGoodsStr", SelectedGoodsStr)
                .addParams("FangFei", fangfei)
                .addParams("coupon_num", coupon_no)
                .addParams("discount_id", discountId)
                .addParams("member_id", isMember ? model.getId() : "0")
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            CreateSelectedGoodsModel createSelectedGoodsModel = gson.fromJson(json, CreateSelectedGoodsModel.class);
                            CreateSelectedGoodsModel.DataBean.OrderInfoBean orderInfo = createSelectedGoodsModel.getData().getOrderInfo();
                            if (!StringUtils.isEmpty(idTvCouponRight.getText().toString())) {
                                if ("0".equals(orderInfo.getCoupon_price())) {
                                    showToast("优惠券不存在");
                                } else {
                                    idTvCouponLeft.setText("优惠券 " + orderInfo.getCoupon_price());
                                }
                            }
                            if ("0".equals(orderInfo.getCoupon_price()) && !isCouponClean) {
                                showToast("优惠券不存在或不可用");
                                coupon_no = "0";
                                idTvCouponRight.setText("");
                                idTvCouponLeft.setText("优惠券");
                                isCouponClean = true;
                            } else {
                                if (isCouponClean) {
                                    idTvCouponLeft.setText("优惠券");
                                    idTvCouponRight.setText("");
                                } else {
                                    idTvCouponLeft.setText("优惠券 " + orderInfo.getCoupon_price());
                                }
//                                        idTvCouponLeft.setText("优惠券 " + paymentAmountModel.getData().getOrderInfo().getCoupon_price());
                            }
                            idTvFitPrice.setText(orderInfo.getZ_discount_price());
                            pey_money = orderInfo.getZ_discount_price();
                            z_special_points = orderInfo.getZ_special_points();
                            special_points_price = orderInfo.getSpecial_points_price();
                            getPoint(orderInfo.getPayment(), "0");
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                    }
                });
    }

    //消费所得积分同个接口
    private void getPoint(String payment, final String input) {
        HttpRequest.postUrl(Api.CONSUMPTION_GET_POINT)
                .addParams("points_replace_before_payment", payment)
                .addParams("payment", payment)
                .addParams("is_input", input)
                .addParams("member_id", isMember ? model.getId() : "0")
                .addParams("discount_id", discountId)
                .addParams("points_replace_points", points_replace_points)
                .addParams("z_special_points", z_special_points)
                .addParams("special_points_price", special_points_price)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            integralMortgageModel = gson.fromJson(json, IntegralMortgageModel.class);
                            if (Float.parseFloat(integralMortgageModel.getData().getPoints_replace_price()) > 0) {
                                idTvIntegerLeft.setText("积分抵扣 -" + integralMortgageModel.getData().getPoints_replace_price());
                            } else {
                                idTvIntegerLeft.setText("积分抵扣");
                            }
                            if ("0".equals(input)) {
                                idTvNowMoney.setText(Utils.ManageMoney(integralMortgageModel.getData().getPayment()));
                                idTvActualMoney.setText(Utils.ManageMoney(integralMortgageModel.getData().getPayment()));
                                idEdtPeyMoney.setText(Utils.ManageMoney(integralMortgageModel.getData().getPayment()));
                            }
                            idTvGetIntegral.setText(integralMortgageModel.getData().getPoints() + "");
                        }
                    }

                    @Override
                    public void onError(Exception e) {

                    }
                });
    }

    //抵用积分，接口回调
    @Override
    public void updateInfo(String integral, String reduce, boolean flag) {
        points_replace_points = integral;
        if (flag) {
            idTvIntegralInfo.setText(integral);
        } else {
            idTvIntegralInfo.setText("");
        }
        getPayment();

    }

    //创建订单
    private void initOrder(String balance_password) {
        getPayMoney();
        EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_CART_INFO_REFRESH, true));
        PostProcess postProcess = HttpRequest.postUrl(httpUrl)
                .addParams("gid", gid)
                .addParams("FangFei", fangfei)
                .addParams("payInfo[payment_type]", payment_type)
                .addParams("orderInfo[OrderInfo][SelectedGoodsStr]", SelectedGoodsStr)
                .addParams("orderInfo[discount_id]", discountId)
                .addParams("payment", idTvNowMoney.getText().toString())
                .addParams("points_replace_before_payment", integralMortgageModel != null ? integralMortgageModel.getData().getPoints_replace_before_payment() : "")
                .addParams("remark", idTvRemarks.getText().toString())
                .addParams("member_id", model != null ? model.getId() : "0")
                .addParams("points_replace_points", idTvIntegralInfo.getText().toString())
                .addParams("payInfo[balance_password]", balance_password)
                .addParams("payInfo[balance_price]", balance_price)
                .addParams("payInfo[cash_price]", cash_price)
                .addParams("payInfo[bank_price]", bank_price)
                .addParams("payInfo[wechat_price]", wechat_price)
                .addParams("payInfo[alipay_price]", alipay_price)
                .addParams("orderInfo[coupon_num]", coupon_no);
        if (idCheckNext.isChecked()) {
            postProcess.addParams("sendConsumeInfo[ConsumeAgain]", "ConsumeAgain");
            postProcess.addParams("sendConsumeInfo[consume_again_time]", idCheckNext.getText().toString());
        }
        postProcess
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            BaseApplication.getSelectedMaps().clear();
                            MobclickAgent.onEvent(mAc, Umeng.CONSUME);
                            showToast("收款成功");
                            ReceivablesCreatOrderModel receivablesCreatOrderModel = gson.fromJson(json, ReceivablesCreatOrderModel.class);
                            GuadanReceivablesSuccessActivity.actionStart(mAc, receivablesCreatOrderModel.getData().getTid(), type, receivablesCreatOrderModel.getData().getLevel_id(), sms, wechat, print);
                            finish();
                        }
                        dismissProgressDialog();
                    }

                    @Override
                    public void onError(Exception e) {
                        dismissProgressDialog();
                    }
                });

    }

    //创建订单
    private void initOrder2(String code) {
        getPayMoney();
        EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_CART_INFO_REFRESH, true));
        PostProcess postProcess = HttpRequest.postUrl(httpUrl)
                .addParams("gid", gid)
                .addParams("payInfo[payment_type]", payment_type)
                .addParams("orderInfo[OrderInfo][SelectedGoodsStr]", SelectedGoodsStr)
                .addParams("orderInfo[discount_id]", discountId)
                .addParams("payment", idTvNowMoney.getText().toString())
                .addParams("points_replace_before_payment", integralMortgageModel != null ? integralMortgageModel.getData().getPoints_replace_before_payment() : "")
                .addParams("remark", idTvRemarks.getText().toString())
                .addParams("member_id", model != null ? model.getId() : "0")
                .addParams("points_replace_points", idTvIntegralInfo.getText().toString())
                .addParams("payInfo[balance_price]", balance_price)
                .addParams("payInfo[cash_price]", cash_price)
                .addParams("payInfo[bank_price]", bank_price)
                .addParams("payInfo[wechat_price]", wechat_price)
                .addParams("payInfo[alipay_price]", alipay_price)
                .addParams("orderInfo[coupon_num]", coupon_no);
        if (idCheckNext.isChecked()) {
            postProcess.addParams("sendConsumeInfo[ConsumeAgain]", "ConsumeAgain");
            postProcess.addParams("sendConsumeInfo[consume_again_time]", idCheckNext.getText().toString());
        }

        if (payment_type.equals("wechat")) {
            postProcess.addParams("payInfo[is_wechat_auth_code]", "1");
            postProcess.addParams("payInfo[wechat_auth_code]", code);
        } else if (payment_type.equals("alipay")) {
            postProcess.addParams("payInfo[is_alipay_auth_code]", "1");
            postProcess.addParams("payInfo[alipay_auth_code]", code);
        }
        postProcess
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCodeNoToast(mAc, json);
                        if (checkCode) {
                            BaseApplication.getSelectedMaps().clear();
                            MobclickAgent.onEvent(mAc, Umeng.CONSUME);
                            showToast("收款成功");
                            ReceivablesCreatOrderModel receivablesCreatOrderModel = gson.fromJson(json, ReceivablesCreatOrderModel.class);
                            GuadanReceivablesSuccessActivity.actionStart(mAc, receivablesCreatOrderModel.getData().getTid(), type, receivablesCreatOrderModel.getData().getLevel_id(), sms, wechat, print);
                            finish();
                        } else {
                            if (json.equals("您使用的私钥格式错误，请检查RSA私钥配置")){
                                dismissProgressDialog();
                                return;
                            }
                            CodeMsgBean codeMsgBean = gson.fromJson(json, CodeMsgBean.class);
                            if (codeMsgBean.getMessage().contains("支付异常")) {
                                PayErrorDialog dialog = new PayErrorDialog(mAc, codeMsgBean.getMessage() + "");
                                dialog.setCanceledOnTouchOutside(false);
                                dialog.show();
                            } else {
                                showToast(codeMsgBean.getMessage() + "");
                            }
                        }
                        dismissProgressDialog();
                    }

                    @Override
                    public void onError(Exception e) {
                        dismissProgressDialog();
                        PayErrorDialog dialog = new PayErrorDialog(mAc, "支付异常，请与对方确认。");
                        dialog.setCanceledOnTouchOutside(false);
                        dialog.show();
//                        showToast("支付超时，请与对方联系。");
                    }
                });

    }

    //支付金额的参数
    private void getPayMoney() {
        switch (payment_type) {
            case "balance":
                balance_price = idTvNowMoney.getText().toString();
                break;
            case "cash":
                cash_price = idEdtPeyMoney.getText().toString();
                break;
            case "bank":
                bank_price = idTvNowMoney.getText().toString();
                break;
            case "wechat":
                wechat_price = idTvNowMoney.getText().toString();
                break;
            case "alipay":
                alipay_price = idTvNowMoney.getText().toString();
                break;
        }

    }

    //确认付款
    @Override
    public void payMoney() {
        showProgressDialog("请稍等，正在创建订单");
        initOrder("");
    }

    //支付密码支付
    @Override
    public void passPay(String pass) {
        showProgressDialog("请稍等，正在创建订单");
        initOrder(pass);
    }

    @Override
    public void selCoupon(boolean flag, String coupon_name, String coupon_no, String left, String payments) {
        isCouponClean = !flag;
        if (flag) {
            this.coupon_no = coupon_no;
            idTvCouponRight.setText(coupon_name);
            idTvCouponLeft.setText("优惠券 " + left);
            getPoint(payments, "0");
        } else {
            this.coupon_no = "0";
            idTvCouponRight.setText("");
            idTvCouponLeft.setText("优惠券");
            getPayment();
        }
    }

    //获取照相机权限
    private static final int MY_PERMISSIONS_REQUEST_CAMERA = 1;

    private void getCameraManifest() {
        MPermissions.requestPermissions(this, MY_PERMISSIONS_REQUEST_CAMERA, Manifest.permission.CAMERA);
    }

    private void getCamera() {
        Intent intent = new Intent(mAc, CaptureActivity.class);
        startActivityForResult(intent, 101);
    }

    @PermissionGrant(MY_PERMISSIONS_REQUEST_CAMERA)
    public void requestSuccess() {
        getCamera();
    }

    @PermissionDenied(MY_PERMISSIONS_REQUEST_CAMERA)
    public void requestError() {
        showToast("授权失败！");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return false;
    }
}
